package com.qianfeng.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.pojo.SysHumiture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/9/14 20:27
 */
@Component
public class HumitureWebSocketHandler extends BaseWebSocket{
    private ApplicationContext context;

    private ObjectMapper objectMapper;
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean isNeedUpdateStatus() {
        return false;
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//        处理一下传过来的温湿度数据
        String payload = message.getPayload();
        try {
            SysHumiture humiture=objectMapper.readValue(payload,SysHumiture.class);
            String deviceId = (String) session.getAttributes().get("deviceId");
            humiture.setDeviceId(deviceId);
            humiture.setTemperature((humiture.getTemperature()-32)/1.8);//获取的温度是华氏,转为摄氏度
//         启动监听器，添加数据到数据库
            context.publishEvent(humiture);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
